package com.wenda.zhou;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class AsyncLoadImageActivity extends Activity {
	final Handler handler2 = new Handler() {
		public void handleMessage(android.os.Message msg) {
			((ImageView) AsyncLoadImageActivity.this.findViewById(msg.arg1))
					.setImageDrawable((Drawable) msg.obj);
		}
	};

	final Handler handler = new Handler();
	private ExecutorService executorService = Executors.newFixedThreadPool(5);

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		loadImage("http://www.chinatelecom.com.cn/images/logo_new.gif",
				R.id.imageView1);
		loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.imageView2);
		loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.imageView3);
		loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.imageView4);
		loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.imageView5);

	}

	public void loadImage1(final String url, final int id) {
		String test="shenli chongtu";
		Thread thread = new Thread() {
			public void run() {
				
				Drawable drawable = null;
				try {
					drawable = Drawable.createFromStream(
							new URL(url).openStream(), "image.png");
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message message = handler2.obtainMessage();
				message.arg1 = id;
				message.obj = drawable;
				String zhouyunogn = "周雨浓改的";
				handler2.sendMessage(message);

			}
		};
		thread.start();
		thread = null;
	}

	public void loadImage(final String url, final int id) {
		executorService.submit(new Runnable() {

			@Override
			public void run() {

				try {
					final Drawable drawable = Drawable.createFromStream(
							new URL(url).openStream(), "image.png");

					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						// TODO: handle exception
					}
					handler.post(new Runnable() {

						@Override
						public void run() {
							((ImageView) AsyncLoadImageActivity.this
									.findViewById(id))
									.setImageDrawable(drawable);

						}
					});

				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

	}

}